package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <h3>springboot-zimg</h3>
 * <p></p>
 *
 * @author : zhengyue
 * @date : 2021-03-13 16:44
 **/
@RestController
public class ImgController {

    private static final String ZIMG_URL = "http://192.168.200.136:4869";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("upload")
    public String upload(MultipartFile file) throws IOException {
        String url = ZIMG_URL + "upload";
        //设置访问参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
//        file.getBytes()
        params.add("blob", file.getBytes());
        params.add("type", "image/jpeg");
        //设置访问的Entity
        HttpEntity entity = new HttpEntity<>(params);
        // 结果
        String result = restTemplate.postForEntity(url, entity, String.class)
                .toString().trim();
        if(result.contains("Image upload successfully!")) {
            int start = result.indexOf("<h1>");
            int end = result.indexOf("</h1>");
            return result.substring(start + 9, end);
        }

        return "上传失败";
    }
}
